package com.siyuanren.gcocp.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.siyuanren.gcocp.common.util.MD5Utils;
import com.siyuanren.gcocp.common.web.bean.Result;
import com.siyuanren.gcocp.service.VideoService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by   anxing
 * Project_name gcocp-parent
 * Path         com.siyuanren.gcocp.service.impl
 * Date         2018/7/4
 * Time         14:08
 * Description 音视频处理相关
 */
@Slf4j
@Service
public class VideoServiceImpl implements VideoService {
    @Override
    public String getAudioUrl(String audioId) {
        Map param = getParam(audioId);

        try {
            String ret = cn.hutool.http.HttpUtil.get("http://union.bokecc.com/api/audio", param, 5000);
            log.info(ret);
            if (ret != null) {
                JSONObject jsonObject = JSON.parseObject(ret);
                JSONObject audio = JSON.parseObject(jsonObject.getString("audio"));
                JSONArray copy = JSON.parseArray(audio.getString("copy"));
                return ((JSONObject) copy.get(0)).get("url").toString();
            } else {
                return null;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public String getVideoUrl(String videoId) {
        Map param = getParam(videoId);

        try {
            String ret = cn.hutool.http.HttpUtil.get("http://union.bokecc.com/api/mobile", param, 5000);
            log.info(ret);
            if (ret != null) {
                JSONObject jsonObject = JSON.parseObject(ret);
                JSONObject audio = JSON.parseObject(jsonObject.getString("video"));
                JSONArray copy = JSON.parseArray(audio.getString("copy"));
                return ((JSONObject) copy.get(0)).get("playurl").toString();
            } else {
                return null;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private Map getParam(String audioId) {
        long time = new Date().getTime();
        StringBuffer sb = new StringBuffer();
        sb.append("authtimeout=").append(360000)
                .append("&format=json")
                .append("&userid=6A2E19DCB918CA38")
                .append("&videoid=").append(audioId)
                .append("&time=").append(time)
                .append("&salt=").append("YJQSwMbbl8kdSjhHyFwI0Za8ruu3J8SK")
        ;
        String md5 = MD5Utils.md5(sb.toString());

        Map param = new HashMap();
        param.put("authtimeout",360000);
        param.put("format","json");
        param.put("userid","6A2E19DCB918CA38");
        param.put("videoid",audioId);
        param.put("time",time);
        param.put("hash",md5);
        return param;
    }
}
